package com.hyjx.framework.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author zengfh
 * @version 1.0
 * date 2018/04/10 12:48
 */
@Configuration
@ConfigurationProperties(prefix = "hyjx.interceptor")
public class InterceptorWebConfig implements WebMvcConfigurer {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(InterceptorWebConfig.class);
    
    private List<String> names;
    
    
    private int DEFAULT_FIRST_INTERCEPTOR_ORDER = Ordered.LOWEST_PRECEDENCE - 1000;
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        
        if (!CollectionUtils.isEmpty(names)) {
            try {
                for (int i = 0; i < names.size(); i++) {
                    registry.addInterceptor((HandlerInterceptor) Class.forName(names.get(i)).newInstance()).order(DEFAULT_FIRST_INTERCEPTOR_ORDER + i);
                }
                LOGGER.debug("拦截器初始化完毕");
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
    
    public List<String> getNames() {
        return names;
    }
    
    public void setNames(List<String> names) {
        this.names = names;
    }
}
